package com.ydlclass.discovery;


import com.ydlclass.Constant;
import com.ydlclass.discovery.impl.NacosRegistry;
import com.ydlclass.discovery.impl.ZookeeperRegistry;
import com.ydlclass.exceptions.DiscoveryException;

/**
 * @author Knife
 */
public class RegistryConfig {

    /**
     * 定义连接的 url zookeeper://127.0.0.1:0000
     */
    private final String connectString;

    public RegistryConfig(String connectString) {
        this.connectString = connectString;
    }

    /**
     * 可以使用简单工厂来进行完成
     * @return 返回具体的注册中心实例
     */
    public Registry getRegistry() {
        // 1、需要获取注册中心的类型
        String registryType = getRegistryType(connectString,true).toLowerCase().trim();
        if ("zookeeper".equals(registryType)){
            String Host = getRegistryType(connectString, false);
            return new ZookeeperRegistry(Host, Constant.TIME_OUT);
        } else if ("nacos".equals(registryType)){
            String Host = getRegistryType(connectString, false);
            return new NacosRegistry(Host, Constant.TIME_OUT);
        }
        throw new DiscoveryException("未发现合适的注册中心");
    }

    private String getRegistryType(String connectString,boolean ifType){
        String[] typeAndHost = connectString.split("://");
        if (typeAndHost.length != 2){
            throw new RuntimeException("给定的注册中心连接url不合法");
        }
        if (ifType){
            return typeAndHost[0];
        } else {
            return typeAndHost[1];
        }
    }

}
